package com.smart.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.smart.core.SpringContext;
import com.smart.model.Menu;
import com.smart.service.MenuService;
import com.smart.util.CollectionUtil;

/**
 * 处理全局前端页面菜单的filter
 * 
 * @author Sunxin
 *
 */
public class MenuFilter implements Filter{

	private MenuService menuService;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		if(menuService==null) {
			menuService = SpringContext.getBean(MenuService.class);
		}
		HttpServletRequest request = (HttpServletRequest) req;
		handleSelectedMenu(request);
	}

	@Override
	public void destroy() {
		
	}
	
	
	private void handleSelectedMenu(HttpServletRequest request) {
		Menu rootMenu = menuService.getMenuTree(Menu.ROOT_MENU_CODE);
		request.setAttribute("rootMenu", rootMenu);
		String sCurMenuId = request.getParameter("curMenuId");
		Long curMenuId = null;
		try {
			curMenuId = Long.parseLong(sCurMenuId);
		}
		catch(Exception e) {
			return;
		}
		Menu menu = menuService.findOne(curMenuId);	
		if(menu==null || menu.getLevel()<2) {
			return;
		}
		Menu parent = menu.getParent();
		parent = menuService.getMenuTree(parent.getId());
		
		List<Menu> list = parent.getChildren();
		if(CollectionUtil.isNotEmpty(list)) {
			for(Menu m : list) {
				if(m.getId().equals(menu.getId())) {
					m.setSelected(true);
				}
			}
		}
		request.setAttribute("menuList", list);
	}


}
